import yaml
import os
from dotenv import load_dotenv

# 加载.env文件
load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), "config", ".env"))

class ConfigUtil:
    @staticmethod
    def _load_yaml_config():
        config_path = os.path.join(
            os.path.dirname(os.path.dirname(__file__)),
            "config", "environments", "config.yaml"
        )
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)

    @staticmethod
    def get_test_url():
        yaml_config = ConfigUtil._load_yaml_config()  # 修正：用类名调用静态方法
        env = yaml_config.get("env", "dev")
        return yaml_config["test_url"][env]

    @staticmethod
    def get_browser():
        # 修正：用类名调用静态方法
        return ConfigUtil._load_yaml_config().get("browser", "chrome").lower()

    @staticmethod
    def get_db_config():
        try:
            return {
                "host": os.getenv("DB_HOST", "localhost"),  # 默认值
                "port": int(os.getenv("DB_PORT", 3306)),  # 默认端口
                "user": os.getenv("DB_USER", "root"),  # 默认用户名
                "password": os.getenv("DB_PASS", ""),  # 默认空密码
                "database": os.getenv("DB_NAME", "test_db")  # 默认数据库名
            }
        except ValueError:
            raise ValueError("DB_PORT must be a valid integer")  # 捕获端口转换异常